package com.yuexia.yxim.client.client;

import com.yuexia.yxim.common.bean.msg.ProtoMsg;
import com.yuexia.yxim.common.bean.msg.User;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * ClientSession
 *
 * @author wjp
 * @date 2020/6/1
 */
@Slf4j
@Data
public class ClientSession {

    public static final AttributeKey<ClientSession> SESSION_KEY =
            AttributeKey.valueOf("SESSION_KEY");


    /**
     * 用户实现客户端管理的channel
     */
    private Channel channel;

    private User user;

    /**
     * 保存登录后的服务端sessionid
     */
    private String sessionId;

    private boolean isConnected = false;
    private boolean isLogin = false;

    /**
     * 绑定通道
     * @param channel
     */
    public ClientSession(Channel channel) {
        this.channel = channel;
        this.sessionId = String.valueOf(-1);
        channel.attr(ClientSession.SESSION_KEY).set(this);
    }

    public static void loginSuccess(ChannelHandlerContext ctx, ProtoMsg.Message pkg) {
        Channel channel = ctx.channel();
        ClientSession clientSession = channel.attr(ClientSession.SESSION_KEY).get();

        clientSession.setSessionId(pkg.getSessionId());
        clientSession.setLogin(true);

        log.info("登录成功");
    }

    /**
     * 获取通道
     * @param ctx
     * @return
     */
    public static ClientSession getSession(ChannelHandlerContext ctx) {
        Channel channel = ctx.channel();
        ClientSession clientSession = channel.attr(ClientSession.SESSION_KEY).get();
        return clientSession;
    }

    public String getRemoteAddresss() {
        return channel.remoteAddress().toString();
    }

    /**
     * 吧protobuf数据包写入通道
     * @param pkg
     * @return
     */
    public ChannelFuture witeAndFlush(Object pkg) {
        return channel.writeAndFlush(pkg);
    }

    public void writeAndClose(Object pkg) {
        ChannelFuture channelFuture = channel.writeAndFlush(pkg);
        channelFuture.addListener(ChannelFutureListener.CLOSE);
    }

    //关闭通道
    public void close() {
        isConnected = false;

        ChannelFuture future = channel.close();
        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    log.error("连接顺利断开");
                }
            }
        });
    }

    public boolean isConnected() {
        return isConnected;
    }

    public boolean isLogin() {
        return isLogin;
    }

}
